<template>
  <basePage :page-params="pageParams">
    <view style="padding: 0 20rpx;">
      <view class="list-bg">
        <view class="avatar_wrap">
          <button
            class="avatar_btn"
            open-type="chooseAvatar"
            @chooseavatar="handleChooseavatar"
          >
            <image class="avatar_img" :src="avatarUrl || vuex_userInfo.avatar || vuex_userInfo.avatarUrl || (vuex_imgPath+'/avatar_icon.png')" />
          </button>
        </view>
        <MenuCell
          :cell-data.sync="menuList"
          :cell-column="cellColumn"
          @handelCellMethod="handelCellMethod"
        />
      </view>
      <u-modal
        :show="modalShow"
        :show-confirm-button="false"
        title="修改昵称"
      >
        <view class="slot-content">
          <view>
            <input v-model="nameFromModal" class="name-inp" type="text" :maxlength="16">
          </view>
          <view class="btn-box">
            <button
              class="btn cancel-btn btn-boundless"
              :plain="true"
              @click="cancelModalFn"
            >
              取消
            </button>
            <button
              class="btn confirm-btn"
              @click="confirmModalFn"
            >
              提交
            </button>
          </view>
        </view>
      </u-modal>
      <u-popup
        :show="popShow"
        :close-on-click-overlay="true"
        mode="bottom"
        :safe-area-inset-bottom="true"
        round="16"
        style="pointer-events: auto;"
        @close="close"
      >
        <view class="pop-content">
          <view class="pop-title">
            <view class="title">修改头像</view>
            <view
              class="close"
            >
              <image
                class="close-icon"
                src="/static/image/close.png"
                @click="close"
              />
            </view>
          </view>
          <view class="content-list">
            <view class="content-item-box" @click="selectPhotoFn">
              <view class="content-item">
                <u-upload
                  name="1"
                  :preview-full-image="false"
                  @afterRead="afterRead"
                >
                  <view style="width: 686rpx;">从相册选择照片</view>
                </u-upload>
              </view>
            </view>
            <view class="content-item-box" @click="close">
              <view class="content-item">取消</view>
            </view>
          </view>
        </view>
      </u-popup>
    </view>
    <!-- 底部按钮栏 -->
    <!-- 由于微信官方更新，此功能暂时注掉 -->
    <!-- <PageFooterBar
      only-btn
      :btn-list="btnList"
      @click="handleUpdateFromWX"
    /> -->
  </basePage>
</template>

<script>
import basePage from '@/components/base-page'
import MenuCell from '@/components/menu-cell'
// import PageFooterBar from '@/components/page-footer-bar'
import { getLoginInfoFn } from '@/common/common'
import { loginQueryMemberInfoV3 } from '@/api/login';
import {
  // updateUserBaseInfo,
  updateHeadPicture,
  modifyUserNikeName
} from '@/api/yc_userInfo';
export default {
  name: 'Index',
  components: {
    basePage,
    MenuCell,
    // PageFooterBar
  },
  data() {
    return {
      avatarUrl: '',
      pageParams: {
        state: null,
        emptyTitle: '',
        errorTitle: '',
        showButton: false
      },
      cellColumn: [
        {
          label: '用户名',
          fields: ['loginAccount'],
          contentStyle: 'font-size: 24rpx;color: #808080;padding-right: 32rpx;'
        },
        // {
        //   label: '姓名',
        //   showRightIcon: true,
        //   fields: ['name'],
        //   contentStyle: 'font-size: 24rpx;color: #808080;',
        //   methodName: 'modifyNameFn'
        // },
        {
          label: '昵称',
          showRightIcon: true,
          fields: ['nickName'],
          contentStyle: 'font-size: 24rpx;color: #808080;',
          methodName: 'modifyNameFn'
        },
        // {
        //   label: '头像',
        //   showRightIcon: true,
        //   rightImg: '',
        //   picStyle: 'width:44rpx;height:44rpx;border-radius: 44rpx;',
        //   methodName: 'modifyAvatarFn',
        //   rightAvatar: true,
        //   avatarEvent: this.handleChooseAvatar
        // }
      ],
      menuList: {
        loginAccount: '',
        name: '',
        avatar: '',
        nickName: ''
      },
      modalShow: false,
      popShow: false,
      nameFromModal: '',
      photoList: [],
      btnList: [
        { name: '微信更新昵称头像', backgroundColor: '#0BB955' }
      ],
      // characterReg: /[`~!@#$%^&*()+=|{}':;',\[\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]/g // 特殊字符
      // characterReg: /(?!.*[\u{1F601}-\u{1F64F}\u{2702}-\u{27B0}\u{1F680}-\u{1F6C0}\u{1F170}-\u{1F251}\u{1F600}-\u{1F636}\u{1F681}-\u{1F6C5}\u{1F30D}-\u{1F567}]|[a-zA-Z]|[\u4e00-\u9fa5]|[0-9])/gu
      characterReg: /[^\u{1F601}-\u{1F64F}\u{2702}-\u{27B0}\u{1F680}-\u{1F6C0}\u{1F170}-\u{1F251}\u{1F600}-\u{1F636}\u{1F681}-\u{1F6C5}\u{1F30D}-\u{1F567}a-zA-Z\u4e00-\u9fa50-9]/gu
    }
  },
  mounted() {
    const {
      headPicPath,
      userName,
      nikeName,
      loginAccount,
      mobilePhone
    } = this.vuex_memberInfo

    this.menuList = {
      loginAccount: loginAccount,
      name: userName,
      nickName: nikeName
    }
    if(this.vuex_memberInfo.accountType == 20){
      this.menuList.loginAccount =userName || mobilePhone
    }
    if(this.vuex_memberInfo.accountType == 30){
    const {
      customerName
    } =this.vuex_crmCustomerInfos[0]
      this.menuList.loginAccount =customerName || ''
    }
    // this.cellColumn[2].rightImg = headPicPath
    this.nameFromModal = nikeName
    this.avatarUrl = headPicPath
  },
  methods: {
    // 更新用户登录信息（存在异步数据，无法用共用方法）
    async updateUserLoginInfo(memberId) {
      const params = { memberId }
      const res = await loginQueryMemberInfoV3(params)
      if (Number(res.code) != 0) {
        uni.$u.toast('获取用户信息失败')
        return false
      }
      /**
   * 账号状态 10：正常； 20：关闭； 30：注销
    */
      // if(res.memberInfo.status ==20 || res.memberInfo.status == 30 || (res.memberInfo.accountType == 30 && !res.crmCustomerInfos)){
      //   uni.$u.toast('该账号无权登录，有问题请联系客服！');
      //     return;
      // }
      uni.$u.vuex('vuex_allMemberInfos', res)
      uni.$u.vuex('vuex_memberInfo', res.memberInfo)
      uni.$u.vuex('vuex_memberCompanyInfo', res.memberCompanyInfo)
      uni.$u.vuex('vuex_crmCustomerInfos', res.crmCustomerInfos)
      uni.$u.vuex('vuex_memberLevelResp', res.memberLevelResp)
    },
    // 微信更新昵称头像
    handleUpdateFromWX() {
      const that = this
      uni.authorize({
        scope: 'scope.userInfo',
        success: (res) => {
          that.getWXUserInfo()
        },
        fail: (res) => {},
        complete: (res) => {},
      })
    },
    // 获取微信用户信息
    getWXUserInfo() {
      uni.getUserInfo({
        withCredentials: true,
        success: async(result) => {
          const { nickName, avatarUrl } = result?.userInfo ?? {}
          const filterNickName = nickName.replace(this.characterReg, '') // 如果包含特殊符号则自动移除
          this.menuList = {
            ...this.menuList,
            avatar: avatarUrl,
            nickName: filterNickName
          }
          const res = await this.updateUserInfo([nickName, avatarUrl])
          if (res.errorCode == 0) {
            this.$u.toast('更新成功')
            const {
              headPicPath,
              userName,
              nikeName
            } = this.vuex_memberInfo
            this.cellColumn[2].rightImg = headPicPath
            this.menuList.nickName = nikeName ?? userName
          }
        },
        fail: (res) => {},
        complete: (res) => {},
      })
    },
    // 更新用户昵称、头像
    async updateUserInfo([nikeName, headPicPath]) {
      const memberId = this.vuex_memberInfo.memberId
      const params = {
        memberId,
        nikeName,
        headPicPath
      }
      const res = await modifyUserNikeName(params)
      if (res.errorCode == 0) {
        await this.updateUserLoginInfo(memberId)
      }
      return res
    },
    handelCellMethod(methodName, val) {
      this[methodName](val)
    },
    /*修改姓名*/
    modifyNameFn() {
      this.modalShow = true
    },
    /*修改头像*/
    modifyAvatarFn(item, e) {
      this.popShow = true
    },
    async confirmModalFn() {
      const hasSpecialCharacter = this.nameFromModal.match(this.characterReg)
      if (hasSpecialCharacter) {
        this.$u.toast('昵称不能包含特殊字符')
        return false
      }
      const nickName = this.nameFromModal.replace(this.characterReg, '')
      if (!nickName) { // 昵称为空不调接口，直接关闭弹窗
        this.modalShow = false
        return false
      }
      const res = await this.updateUserInfo([nickName])
      if (res.errorCode == 0) {
        this.$u.toast('昵称更新成功')
        this.menuList.nickName = this.vuex_memberInfo.nikeName
        this.modalShow = false
      } else {
        this.$u.toast(res.msg)
      }
    },
    selectPhotoFn() {
      this.popShow = true
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      const lists = [].concat(event.file)
      let photoListLen = this[`photoList`].length
      lists.map((item) => {
        this[`photoList`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        await this.uploadFilePromise(lists[i].url).then((picUrl) => {
          const item = this[`photoList`][photoListLen]
          this[`photoList`].splice(photoListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: picUrl
          }))
          const params = {
            headPicPath: picUrl
          }
          updateHeadPicture(params).then((res) => {
            if (res.errorCode == 0) {
              this.$u.toast('修改成功')
              this.cellColumn[2].rightImg = picUrl
              this.popShow = false
              getLoginInfoFn(this.vuex_memberInfo.memberId)
            } else {
              this.$u.toast(res.msg)
            }
          })
        })
        photoListLen++
      }
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: `${this.vuex_baseURL.ycUrl}/baseservice/uploadForIE8`, // 仅为示例，非真实的接口地址
          filePath: url,
          name: 'file',
          formData: {},
          success: (res) => {
            setTimeout(() => {
              resolve(JSON.parse(res.data)[0].fullPath)
            }, 1000)
          }
        });
      })
    },
    cancelModalFn() {
      this.modalShow = false
    },
    close() {
      this.popShow = false
    },
    // 选择头像
    async handleChooseavatar(e) {
      const { avatarUrl } = e.detail ?? {}
      const params = { headPicPath: avatarUrl }
      const res = await updateHeadPicture(params)
      if (res.errorCode == 0) {
        this.avatarUrl = avatarUrl
        getLoginInfoFn(this.vuex_memberInfo.memberId)
      } else {
        this.$u.toast(res.msg)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.name-inp{
  width: 476rpx;
  height: 72rpx;
  border: 2rpx solid $uni-grey-e2;
  border-radius: $uni-border-radius-default;
  padding-left: 32rpx;
  font-size: $uni-font-size-base;
}
.btn{
  width: 220rpx;
  margin: 48rpx 12rpx 0;
  height: 72rpx;
  line-height: 72rpx;
  font-size: $uni-font-size-base;
  display: inline-block;
  color: $uni-text-color;
}
.cancel-btn{
  margin-right: 36rpx;
  background: $uni-bg-color;
}
.confirm-btn{
  color: #fff;
  background: $uni-orange;
  padding:0 24rpx;
  border: 0;
}
.pop-content{
  height: 380rpx;
  .pop-title{
    width: calc(100% - 64rpx);
    height: 88rpx;
    border-bottom: 2rpx solid $uni-grey-e2;
    padding: 0 32rpx 0 32rpx;
    .title{
      width: 120rpx;
      height: 88rpx;
      line-height: 88rpx;
      font-size: $uni-font-size-base;
      font-weight: 700;
      float: left;
    }
    .close{
      width: 48rpx;
      height: 48rpx;
      float: right;
      margin: 24rpx 0;
      .close-icon{
        width: 48rpx;
        height: 48rpx;
      }
    }
  }
  .content-list{
    text-align: center;
    .content-item-box{
      width: 686rpx;
      margin: 0 auto;
      border-bottom: 2rpx solid $uni-f5bg-color;
      .content-item{
        width: 100%;
        height: 98rpx;
        font-size: $uni-font-size-base;
        line-height: 98rpx;
        margin: 0 auto;
      }
    }
  }
}
/deep/ .u-upload{
  width: 100%!important;
}

.avatar_wrap {
  width: 100%;
  display: flex;
  justify-content: center;
  border-bottom: 1rpx solid #f5f5f5;
  .avatar_btn {
    width: 150rpx;
    height: 150rpx;
    margin: 50rpx 0rpx;
    padding-left: 0rpx;
    background-color: transparent;
    .avatar_img {
      width: 150rpx;
      height: 150rpx;
    }
  }
}
</style>
